import 'package:flutter/material.dart';
import 'nft_transaction_success_screen.dart';

class NFTTransactionConfirmScreen extends StatefulWidget {
  final Map<String, dynamic> nftData;

  const NFTTransactionConfirmScreen({
    Key? key,
    required this.nftData,
  }) : super(key: key);

  @override
  State<NFTTransactionConfirmScreen> createState() => _NFTTransactionConfirmScreenState();
}

class _NFTTransactionConfirmScreenState extends State<NFTTransactionConfirmScreen> {
  String selectedPaymentMethod = 'USDT';
  
  @override
  Widget build(BuildContext context) {
    final nft = widget.nftData;
    final price = double.parse(nft['price']);
    final fee = price * 0.001; // 0.1% 手续费
    final totalAmount = price + fee;
    
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF666666)),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          '购买确认',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Color(0xFF333333),
          ),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 20,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                padding: const EdgeInsets.all(30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // NFT信息展示
                    Row(
                      children: [
                        // NFT图片
                        Container(
                          width: 120,
                          height: 120,
                          decoration: BoxDecoration(
                            color: nft['categoryBgColor'] ?? const Color(0xFFE6F7FF),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                nft['category'] ?? '苏绣',
                                style: TextStyle(
                                  fontSize: 24,
                                  fontWeight: FontWeight.bold,
                                  color: nft['categoryTextColor'] ?? const Color(0xFF1890FF),
                                ),
                              ),
                              const SizedBox(height: 8),
                              Text(
                                nft['artworkName'] ?? '《牡丹图》',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: nft['categoryTextColor'] ?? const Color(0xFF1890FF),
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(width: 20),
                        // NFT信息
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                nft['name'] ?? '苏绣非遗传承人作品',
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xFF333333),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                '作者: ${nft['author'] ?? '张明'}',
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Color(0xFF666666),
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                '编号: HRC-NFT-2023-001',
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: Color(0xFF666666),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    
                    // 价格信息
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF0F2F5),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            'NFT价格',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFF666666),
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(
                            '${_formatPrice(nft['price'])} USDT',
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF333333),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 支付方式
                    const Text(
                      '支付方式',
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFF666666),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF0F2F5),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Text(
                            'USDT',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF333333),
                            ),
                          ),
                          Icon(
                            Icons.keyboard_arrow_down,
                            color: const Color(0xFF666666),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 手续费信息
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                        color: const Color(0xFFF0F2F5),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '手续费',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFF666666),
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(
                            '0.1% (${fee.toStringAsFixed(1)} USDT)',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF333333),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 总额信息
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFFF7E0),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '应付总额',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFF666666),
                            ),
                          ),
                          const SizedBox(height: 5),
                          Text(
                            '${totalAmount.toStringAsFixed(1)} USDT',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF333333),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 20),
                    
                    // 风险提示
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(15),
                      decoration: BoxDecoration(
                        color: const Color(0xFFFFF1F0),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '风险提示:',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFFF5222D),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(height: 8),
                          Text(
                            '1. NFT交易具有唯一性，一旦购买成功概不退款',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFFF5222D),
                            ),
                          ),
                          SizedBox(height: 4),
                          Text(
                            '2. 请确认NFT信息无误后再提交订单',
                            style: TextStyle(
                              fontSize: 14,
                              color: Color(0xFFF5222D),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          
          // 确认购买按钮
          Container(
            padding: const EdgeInsets.all(20),
            child: SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: () {
                  _confirmPurchase();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF1890FF),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                ),
                child: const Text(
                  '确认购买',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  String _formatPrice(String price) {
    final num = double.parse(price);
    return num.toStringAsFixed(0).replaceAllMapped(
      RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]},',
    );
  }
  
  void _confirmPurchase() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认购买'),
          content: Text('确定要购买 ${widget.nftData['name']} 吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _processPurchase();
              },
              child: const Text('确认'),
            ),
          ],
        );
      },
    );
  }
  
  void _processPurchase() {
    // 模拟购买处理
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return const AlertDialog(
          content: Row(
            children: [
              CircularProgressIndicator(),
              SizedBox(width: 20),
              Text('正在处理购买...'),
            ],
          ),
        );
      },
    );

    // 模拟网络请求延迟
    Future.delayed(const Duration(seconds: 2), () {
      Navigator.of(context).pop(); // 关闭加载对话框
      
      // 生成模拟交易数据
      final String transactionId = 'HRC-NFT-${DateTime.now().millisecondsSinceEpoch}';
      final String purchaseTime = DateTime.now().toString().substring(0, 19);
      final double purchasePrice = widget.nftData['price']?.toDouble() ?? 0.0;
      final double fee = purchasePrice * 0.001; // 0.1% 手续费
      
      // 跳转到交易成功页面
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => NFTTransactionSuccessScreen(
            nftData: widget.nftData,
            transactionId: transactionId,
            purchaseTime: purchaseTime,
            purchasePrice: purchasePrice,
            fee: fee,
          ),
        ),
      );
    });
  }
}